from flask import Flask, request, jsonify

app = Flask(__name__)
users = {
    "admin": {
        "username": "admin",
        "password": "admin_pass", 
        "role": "admin"
    }
}
products = {"1": {"name": "Laptop", "price": 1000, "stock": 5}}
orders = []
discounts = {"PENTEST_API": 0.1}  # 10% discount

@app.route('/register', methods=['POST'])
def register():
    data = request.json
    username = data['username']

    if username in users:
        return jsonify({"error": "User already exists"}), 400
    users[username] = {
        "username": username, "password": data['password'], "role": "user"
    }
    return jsonify({"message": "User registered successfully"}), 201

@app.route('/order', methods=['POST'])
def place_order():
    data = request.json
    username = data['username']
    product_id = data['product_id']
    quantity = data['quantity']
    discount_code = data.get('discount_code')

    if username not in users:
        return jsonify({"error": "User not found"}), 404

    if product_id not in products:
        return jsonify({"error": "Product not found"}), 404

    if products[product_id]['stock'] < quantity:
        return jsonify({"error": "Insufficient stock"}), 400

    price = products[product_id]['price'] * quantity

    if discount_code and discount_code in discounts:
        price -= price * discounts[discount_code]

    order = {
        "username": username, "product_id": product_id, "quantity": quantity, 
        "total_price": price
    }
    orders.append(order)
    products[product_id]['stock'] -= quantity
    return jsonify({"message": "Order placed successfully", "order": order}), 200

@app.route('/admin', methods=['POST'])
def admin():
    data = request.json

    if (
        data.get('username') != 'admin' or
        data.get('password') != users['admin']['password']
       ):
        return jsonify({"error": "Unauthorized"}), 403

    action = data.get('action')
    if action == 'view_orders':
        return jsonify(orders), 200
    if action == 'add_discount':
        code = data.get('code')
        discount = data.get('discount')
        discounts[code] = discount  # Unauthorized admin function access
        return jsonify({"message": "Discount added"}), 200

    return jsonify({"error": "Invalid action"}), 400

if __name__ == '__main__':
    app.run(debug=True)
